<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\Policy;
use app\common\model\PolicyRelation;
use app\common\model\Product;
use app\common\model\ProductApply;
use app\common\model\User;
use think\Db;

class Team extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 获取代理申请产品列表
     */
    public function getApplyProduct()
    {
        $team = Lib::getTeamProductApplyList(2, $this->auth->id);
        $this->success("获取成功", $team);
    }

    /**
     * 获取代理申请产品及产品所有政策
     */
    public function getAgencyProductPolicy()
    {
        $id = $this->request->post('id');
        $product_apply = ProductApply::get($id);
        $product = Product::where('id', 'in', $product_apply->product_ids)->select();
        foreach ($product as $key => $val) {
            $product[$key]["policy"] = Lib::getSubordinatePolicy($val->id, 2, $this->auth->id);
        }
        $this->success("获取成功", $product);
    }

    /**
     * 设置代理产品政策
     */
    public function setApplyProductPolicy()
    {
        $id = $this->request->post('id');
        $product = $this->request->post('product/a');
        $product_apply = ProductApply::get($id);
        if (!empty($product)) {
            foreach ($product as $val) {
                self::saveProductPolicyRelation($product_apply->main_id, $val);
            }
            ProductApply::where(["id" => $id])->update(['status' => 1]);
            User::where(["id" => $product_apply->main_id])->update(['is_setting' => 1]);
        }
        $this->success("设置成功");
    }

    /**
     * 保存代理政策
     */
    public static function saveProductPolicyRelation($userid, $data, $mainType = 2)
    {
        $res = false;
        $where = [
            "main_type" => $mainType,
            "main_id" => $userid,
            "product_id" => $data['product_id'],
            "policy_id" => $data['policy_id']
        ];
        $policy_relation = PolicyRelation::where($where)->find();
        if ($data['default'] == 1) {
            PolicyRelation::where(["main_type" => 2, "main_id" => $userid, "product_id" => $data['product_id']])->update(["default" => 0]);
        }
        if ($policy_relation) {
            if ($data['default'] == 1) {
                $res = PolicyRelation::where('id', $policy_relation["id"])->update(["default" => $data["default"], "default_time" => time()]);
            }
        } else {
            $policy_relation = new \app\common\model\PolicyRelation();
            $policy_relation->main_type = 2;
            $policy_relation->main_id = $userid;
            $policy_relation->product_id = $data['product_id'];
            $policy_relation->policy_id = $data['policy_id'];
            $policy_relation->default = $data['default'];
            $policy_relation->default_time = time();
            $res = $policy_relation->save();
        }
        return $res;
    }

    /**
     * 获取我的团队
     */
    public function getMyTeamList()
    {
        $type = $this->request->post('type', 1);
        $fields = "id,nickname name,REPLACE(username, SUBSTR(mobile,4,4), '****') phone,FROM_UNIXTIME(jointime,'%Y-%m-%d %H:%m:%s') jointime";
        $team = User::where(['pid' => $this->auth->id, 'ptype' => 2, 'is_virtual' => 1])->field($fields)->order('createtime desc')->select();
        if ($type == 2) {
            if ($this->auth->pid > 0) {
                $arr[] = User::where(['id' => $this->auth->pid])->field($fields)->find();
                foreach($team as $key => $val) {
                    $arr[] = $val;
                }
            } else {
                $arr = $team;
            }
        } else {
            $arr = $team;
        }
        $this->success('获取成功', $arr);
    }

    /**
     * 产品代理 获取我可以代理的产品
     */
    public function getTopAgencyProduct()
    {
        $data = Lib::getMyProduct5($this->auth->pid, $this->auth->ptype);
        $this->success('获取成功', $data);
    }

    /**
     * 产品代理 提交我的代理
     */
    public function saveAgencyProduct()
    {
        $productId = $this->request->post('product_id/a');
        if (!empty($productId) && count($productId) > 0) {
            $where = [
                "main_type" => 2,
                "main_id" => $this->auth->id,
                "product_ids" => implode(',', $productId),
                "status" => 0
            ];
            $count = ProductApply::where($where)->count();
            if ($count <= 0) {
                $nums = 0;
                foreach ($productId as $val) {
                    $stock = Lib::getStocks(2, $this->auth->id, $val);
                    if (!empty($stock)) {
                        $nums += $stock["stocks"];
                    }
                }
                if ($nums <= 0) {
                    $where["create_time"] = time();
                    $res = ProductApply::create($where);
                    if ($res) {
                        $this->success('提交申请成功，请您耐心等待');
                    } else {
                        $this->error("提交申请失败，请重新操作！");
                    }
                } else {
                    $this->error("存在未清理的库存，无法申请代理！");
                }
            } else {
                $this->error("您已经申请过该产品代理了！");
            }
        } else {
            $this->error("请选择要代理的产品！");
        }
    }

    /**
     * 删除代理申请
     */
    public function delPolicyRelation()
    {
        $id = $this->request->post('id');
        if (!empty($id) && $id > 0) {
            $data = ProductApply::get($id);
            if ($data->status == 0) {
                $res = ProductApply::where('id', $id)->delete();
                if ($res) {
                    $this->success('删除成功！');
                } else {
                    $this->error("删除失败，请联系系统客服！");
                }
            } else {
                $this->error("操作失败，请重新操作！");
            }
        } else {
            $this->error("参数错误！");
        }
    }

    // 获取代理详细信息
    public function getTeamDetail()
    {
        $id = $this->request->post('id');
        if (!empty($id) && $id > 0) {
            $data = User::get($id);
            $this->success('代理信息', $data);
        } else {
            $this->error("参数错误！");
        }
    }

    // 设置团队提现状态
    public function setTeamWithdrawState()
    {
        $id = $this->request->post('id');
        $withdrawState = $this->request->post('withdraw_state');
        if (!empty($id) && $id > 0 && !empty($withdrawState) && $withdrawState > 0) {
            // 开启提现功能
            if ($withdrawState == 1) {
                $team = User::get($id);
                if ($team->withdraw_state == 2) {
                    $team->withdraw_state = 1;
                    $team->save();
                    self::setWithdrawStateLog($this->auth->id, $id, $withdrawState, $id);
                    $this->success('开启成功');
                } else {
                    $this->error("该成员提现功能已开启！");
                }
            } else {
                // 关闭提现功能
                $teamIds = Lib::getTeamAllUser($id);
                if (!empty($teamIds)) {
                    Db::name('user')->whereIn("id", $teamIds)->update(["withdraw_state" => 2]);
                    self::setWithdrawStateLog($this->auth->id, $id, $withdrawState, implode(",", $teamIds));
                    $this->success('关闭成功');
                } else {
                    $this->error("操作失败，请联系上级！");
                }
            }
        } else {
            $this->error("参数错误！");
        }
    }

    public static function setWithdrawStateLog($operateId, $userId, $types, $teamIds)
    {
        $data = [
            "operate_id" => $operateId,
            "user_id" => $userId,
            "types" => $types,
            "team_ids" => $teamIds,
            "create_time" => time()
        ];
        Db::name("withdraw_state_log")->insert($data);
    }
}
